import router from './router';
// import NProgress from 'nprogress'; // progress bar
// import '@/components/NProgress/nprogress.less'; // progress bar custom style
// import notification from 'ant-design-vue/es/notification';
import { setDocumentTitle } from '@/utils/util';
import { ACCESS_TOKEN } from './store/user';
import { useUserStore } from './store';

// NProgress.configure({ showSpinner: false }); // NProgress Configuration

const allowList = ['login', 'register', 'registerResult']; // no redirect allowList
const loginRoutePath = '/login';
const defaultRoutePath = '/';

let done = false;

router.beforeEach((to, from, next) => {
  // NProgress.start(); // start progress bar
  if (to.meta && 'title' in to.meta && typeof to.meta.title === 'string') {
    setDocumentTitle(to.meta.title);
  }
  /* has token */
  const token = sessionStorage.getItem(ACCESS_TOKEN);
  if (token) {
    const userStore = useUserStore();
    if (!done && userStore.privilege) {
      userStore.setMenu();
      userStore.routes.forEach(r => {
        router.addRoute(r);
      });

      router.addRoute({ path: '/:pathMatch(.*)*', redirect: '/404' });

      done = true;
      next({ ...to, replace: true });
      return;
    }
    if (to.path === loginRoutePath) {
      next({ path: defaultRoutePath });
      // NProgress.done();
    } else {
      next();
    }
  } else {
    if (allowList.includes(to.name as string)) {
      // 在免登录名单，直接进入
      next();
    } else {
      next({ path: loginRoutePath, query: { redirect: to.fullPath } });
      // NProgress.done(); // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
});

router.afterEach(() => {
  // NProgress.done(); // finish progress bar
});
